<?php
class Cache_MySQL_Driver implements Cache_Driver {
	public function __construct() {
		$this->db = new Database();
	}
	
	public function set($id, $data, array $tags = array(), $lifetime) {
		if (strlen($id) > 400 || empty($id)) {
			trigger_error('Invalid or too long cache key length.', E_ERROR);
		}
		
		$this->db->query('
			INSERT INTO
				forum_kohana_cache
				(itemId, itemHash, tags, value, ttl)
			VALUES
				(
				?,
				?,
				?,
				?,
				?
				)
			ON DUPLICATE KEY UPDATE
				`value` = ?,
				`ttl` = ?
		', array(
			$id,
			sha1($id),
			implode(' ', $tags),
			serialize($data),
			time() + $lifetime,
			serialize($data),
			time() + $lifetime,
			$id
		));
		
		return true;
	}

	/**
	 * Find all of the cache ids for a given tag.
	 */
	public function find($tag) {
		//
	}

	/**
	 * Get a cache item.
	 * Return NULL if the cache item is not found.
	 */
	public function get($id) {
		$result = $this->db->query('
		
			SELECT
				itemId, value
			FROM
				forum_kohana_cache
			WHERE
				itemHash = ?
		
		', array(
			sha1($id)
		))->result_array(false);
		
		var_dump($result);
		
		if (count($result) == 1) {
			return unserialize($result[0]['value']);
		} elseif (count($result) > 1) {
			foreach ($result as $r) {
				if ($r['itemId'] == $id) {
					return unserialize($r['value']);
				}
			}
		} else {
			return NULL;	
		}
	}

	/**
	 * Delete cache items by id or tag.
	 */
	public function delete($id, $tag = FALSE) {
		if (!empty($id)) {
			$this->db->query('
				DELETE FROM
					forum_kohana_cache
				WHERE
					itemId = ?
			', array(
				$id
			));
		} elseif (!empty($tag)) {
			$this->db->query('
				DELETE FROM
					forum_kohana_cache
				WHERE
					MATCH (tags) IN BOOLEAN MODE AGAINST (?)
			', array(
				$tag
			));
		}
	}

	/**
	 * Deletes all expired cache items.
	 */
	public function delete_expired() {
		$this->db->query('
			DELETE FROM
				forum_kohana_cache
			WHERE
				ttl < ?
		', array(
			time()
		));
	}
}
